<template>
	<!-- 自定义补贴金额公式编辑器 -->
	<el-dialog
		v-model="visible"
		title="自定义补贴金额"
		width="800px"
		:close-on-click-modal="false"
		:close-on-press-escape="false"
		@closed="handleClosed"
	>
		<div class="formula-dialog-content">
			<!-- 顶部提示信息 -->
			<div class="formula-info">
				<el-icon><InfoFilled /></el-icon>
				<span>通过输入四则运算的方式来定义补贴金额的计算规则</span>
			</div>

			<div class="formula-editor-container">
				<!-- 左侧字段选择器 -->
				<div class="field-selector">
					<div class="field-search">
						<el-input v-model="fieldSearchKeyword" placeholder="搜索字段名" prefix-icon="Search" clearable />
					</div>
					<div class="field-list">
						<div class="field-group">
							<div class="field-group-title" @click="toggleFieldGroup">
								<span>分组</span>
								<el-icon :class="{ 'is-expanded': fieldGroupExpanded }">
									<ArrowDown />
								</el-icon>
							</div>
							<div v-show="fieldGroupExpanded" class="field-items">
								<div v-for="field in filteredFields" :key="field.key" class="field-item" @click="insertField(field)">
									{{ field.label }}
								</div>
							</div>
						</div>
					</div>
				</div>

				<!-- 右侧公式编辑器 -->
				<div class="formula-editor">
					<!-- 运算符按钮 -->
					<div class="operator-buttons">
						<el-button v-for="operator in operators" :key="operator" size="small" @click="insertOperator(operator)">
							{{ operator }}
						</el-button>
					</div>

					<!-- 操作指引 -->
					<div class="operation-guide">
						<el-button link size="small" @click="showOperationGuide">
							<el-icon><QuestionFilled /></el-icon>
							操作指引
						</el-button>
					</div>

					<!-- 公式输入区 -->
					<div class="formula-input-area">
						<el-input
							v-model="tempFormula"
							type="textarea"
							:rows="6"
							placeholder="请在此输入计算公式，可通过点击左侧字段或右侧运算符按钮快速输入"
							@input="validateFormula"
						/>
					</div>

					<!-- 公式示例 -->
					<div class="formula-example">
						<el-checkbox v-model="useExample" @change="applyExample"> 公式示例: 社会工作年限 + 入司年限 × 10 </el-checkbox>
					</div>
				</div>
			</div>
		</div>

		<template #footer>
			<div class="dialog-footer">
				<el-button @click="handleCancel">取消</el-button>
				<el-button type="primary" @click="handleConfirm" :disabled="!tempFormula.trim()"> 确定 </el-button>
			</div>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, nextTick, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { InfoFilled, ArrowDown, QuestionFilled, Search } from '@element-plus/icons-vue';

// 定义组件的 props
interface Props {
	modelValue: boolean;
	formula?: string;
}

// 定义组件的 emits
interface Emits {
	(e: 'update:modelValue', value: boolean): void;
	(e: 'confirm', formula: string): void;
	(e: 'cancel'): void;
}

const props = withDefaults(defineProps<Props>(), {
	modelValue: false,
	formula: '',
});

const emit = defineEmits<Emits>();

// 响应式数据
const tempFormula = ref('');
const fieldSearchKeyword = ref('');
const fieldGroupExpanded = ref(true);
const useExample = ref(false);

// 可用字段列表
const availableFields = ref([
	{ key: 'socialWorkYears', label: '社会工作年限' },
	{ key: 'companyYears', label: '入司年限' },
	{ key: 'dailyAttendanceMinutes', label: '当日出勤时长(分钟)' },
]);

// 运算符列表
const operators = ref(['+', '-', '×', '÷', '(', ')']);

// 计算属性
const visible = computed({
	get: () => props.modelValue,
	set: (value: boolean) => emit('update:modelValue', value),
});

// 过滤后的字段列表
const filteredFields = computed(() => {
	if (!fieldSearchKeyword.value) return availableFields.value;
	return availableFields.value.filter((field) => field.label.toLowerCase().includes(fieldSearchKeyword.value.toLowerCase()));
});

// 监听弹窗打开，初始化公式内容
watch(visible, (newVal) => {
	if (newVal) {
		tempFormula.value = props.formula || '';
		resetDialog();
	}
});

// 方法定义
const resetDialog = () => {
	fieldSearchKeyword.value = '';
	useExample.value = false;
	fieldGroupExpanded.value = true;
};

const toggleFieldGroup = () => {
	fieldGroupExpanded.value = !fieldGroupExpanded.value;
};

const insertField = (field: { key: string; label: string }) => {
	const textarea = document.querySelector('.formula-input-area textarea') as HTMLTextAreaElement;
	if (textarea) {
		const start = textarea.selectionStart;
		const end = textarea.selectionEnd;
		const currentValue = tempFormula.value;
		const newValue = currentValue.substring(0, start) + field.label + currentValue.substring(end);
		tempFormula.value = newValue;

		// 设置光标位置
		nextTick(() => {
			textarea.focus();
			textarea.setSelectionRange(start + field.label.length, start + field.label.length);
		});
	}
};

const insertOperator = (operator: string) => {
	const textarea = document.querySelector('.formula-input-area textarea') as HTMLTextAreaElement;
	if (textarea) {
		const start = textarea.selectionStart;
		const end = textarea.selectionEnd;
		const currentValue = tempFormula.value;
		const newValue = currentValue.substring(0, start) + operator + currentValue.substring(end);
		tempFormula.value = newValue;

		// 设置光标位置
		nextTick(() => {
			textarea.focus();
			textarea.setSelectionRange(start + operator.length, start + operator.length);
		});
	}
};

const validateFormula = () => {
	// 这里可以添加公式验证逻辑
	// 例如检查括号匹配、运算符使用等
};

const showOperationGuide = () => {
	ElMessage.info(
		'操作指引：\n1. 点击左侧字段可插入到公式中\n2. 点击右侧运算符按钮可插入运算符\n3. 支持四则运算和括号\n4. 公式示例：社会工作年限 + 入司年限 × 10'
	);
};

const applyExample = (checked: boolean) => {
	if (checked) {
		tempFormula.value = '社会工作年限 + 入司年限 × 10';
	} else {
		tempFormula.value = '';
	}
};

const handleConfirm = () => {
	if (!tempFormula.value.trim()) {
		ElMessage.warning('请输入计算公式');
		return;
	}

	emit('confirm', tempFormula.value.trim());
	visible.value = false;
	ElMessage.success('公式设置成功');
};

const handleCancel = () => {
	emit('cancel');
	visible.value = false;
};

const handleClosed = () => {
	resetDialog();
};

// 暴露给父组件的方法和数据
defineExpose({
	tempFormula,
	resetDialog,
});
</script>

<style lang="scss" scoped>
/* 补充计算公式相关样式 */
.formula-dialog-content {
	padding: 0;

	.formula-info {
		display: flex;
		align-items: center;
		gap: 8px;
		padding: 12px 16px;
		background-color: var(--el-color-info-light-9);
		border: 1px solid var(--el-color-info-light-5);
		border-radius: 6px;
		margin-bottom: 20px;
		color: var(--el-color-info-dark-2);
		font-size: 14px;
	}

	.formula-editor-container {
		display: flex;
		gap: 20px;
		min-height: 400px;

		.field-selector {
			width: 250px;
			border: 1px solid var(--el-border-color);
			border-radius: 6px;
			background-color: var(--el-fill-color-lighter);

			.field-search {
				padding: 12px;
				border-bottom: 1px solid var(--el-border-color);
			}

			.field-list {
				padding: 0;

				.field-group-title {
					display: flex;
					justify-content: space-between;
					align-items: center;
					padding: 12px 16px;
					cursor: pointer;
					font-weight: 500;
					color: var(--el-text-color-primary);
					background-color: var(--el-fill-color);
					border-bottom: 1px solid var(--el-border-color);

					&:hover {
						background-color: var(--el-color-primary-light-9);
					}

					.el-icon {
						transition: transform 0.3s ease;

						&.is-expanded {
							transform: rotate(180deg);
						}
					}
				}

				.field-items {
					padding: 0;

					.field-item {
						padding: 10px 16px;
						cursor: pointer;
						border-bottom: 1px solid var(--el-border-color-extra-light);
						font-size: 14px;
						color: var(--el-text-color-regular);
						transition: background-color 0.2s ease;

						&:hover {
							background-color: var(--el-color-primary-light-9);
							color: var(--el-color-primary);
						}

						&:last-child {
							border-bottom: none;
						}
					}
				}
			}
		}

		.formula-editor {
			flex: 1;
			display: flex;
			flex-direction: column;
			gap: 16px;

			.operator-buttons {
				display: flex;
				gap: 8px;
				flex-wrap: wrap;

				.el-button {
					min-width: 40px;
					height: 32px;
					font-size: 16px;
					font-weight: 500;
				}
			}

			.operation-guide {
				display: flex;
				justify-content: flex-end;
			}

			.formula-input-area {
				flex: 1;

				.el-textarea {
					height: 100%;

					:deep(.el-textarea__inner) {
						font-family: 'Courier New', monospace;
						font-size: 14px;
						line-height: 1.5;
					}
				}
			}

			.formula-example {
				padding: 12px;
				background-color: var(--el-fill-color);
				border: 1px solid var(--el-border-color-light);
				border-radius: 6px;

				.el-checkbox {
					font-size: 14px;
					color: var(--el-text-color-regular);
				}
			}
		}
	}

	.dialog-footer {
		display: flex;
		justify-content: flex-end;
		gap: 12px;
		padding-top: 20px;
		border-top: 1px solid var(--el-border-color);
	}
}

/* 暗黑模式适配 */
[data-theme='dark'] {
	.formula-dialog-content {
		.formula-info {
			background-color: var(--next-color-hover) !important;
			border-color: var(--next-border-color) !important;
			color: var(--next-color-bar) !important;
		}

		.field-selector {
			background-color: var(--next-color-primary) !important;
			border-color: var(--next-border-color) !important;

			.field-search {
				border-bottom-color: var(--next-border-color) !important;
			}

			.field-group-title {
				color: var(--next-color-bar) !important;
				background-color: var(--next-color-hover) !important;
				border-bottom-color: var(--next-border-color) !important;

				&:hover {
					background-color: var(--next-color-hover-rgba) !important;
				}
			}

			.field-item {
				color: var(--next-text-color-regular) !important;
				border-bottom-color: var(--next-border-color) !important;

				&:hover {
					background-color: var(--next-color-hover-rgba) !important;
					color: var(--el-color-primary) !important;
				}
			}
		}

		.formula-example {
			background-color: var(--next-color-hover) !important;
			border-color: var(--next-border-color) !important;

			.el-checkbox {
				color: var(--next-text-color-regular) !important;
			}
		}

		.dialog-footer {
			border-top-color: var(--next-border-color) !important;
		}
	}
}

/* 响应式设计 */
@media (max-width: 1200px) {
	.formula-dialog-content {
		.formula-editor-container {
			flex-direction: column;
			gap: 16px;

			.field-selector {
				width: 100%;
			}
		}
	}
}

@media (max-width: 768px) {
	.formula-dialog-content {
		.formula-editor-container {
			min-height: 300px;

			.field-selector {
				.field-item {
					padding: 8px 12px;
					font-size: 13px;
				}
			}

			.operator-buttons {
				.el-button {
					min-width: 35px;
					height: 28px;
					font-size: 14px;
				}
			}
		}
	}
}

@media (max-width: 480px) {
	.formula-dialog-content {
		.formula-editor-container {
			min-height: 250px;
			gap: 12px;

			.field-selector {
				.field-group-title {
					padding: 8px 12px;
					font-size: 13px;
				}

				.field-item {
					padding: 6px 12px;
					font-size: 12px;
				}
			}

			.operator-buttons {
				.el-button {
					min-width: 30px;
					height: 26px;
					font-size: 12px;
				}
			}

			.formula-input-area {
				:deep(.el-textarea__inner) {
					font-size: 12px;
				}
			}
		}
	}
}
</style>
